package com.unicom.mec.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.unicom.mec.user.common.ResultBean;
import com.unicom.mec.user.mapper.UserMapper;
import com.unicom.mec.user.model.User;
import com.unicom.mec.user.vo.TenantVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 租户业务处理实现
 *
 * @author 刘亮武
 * @date 2020年06月11日
 */
@Service
public class TenantServiceImpl implements TenantService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Long findTenantIdByUniqueKey(String uniqueKey) {
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.eq("unique_key",uniqueKey);
        List<User> users = userMapper.selectList(userQuery);
        if(users == null){
            return 0L;
        }
        return users.get(0).getId();
    }

    @Override
    public TenantVo findTenantById(Long id) {
        TenantVo tenantVo = userMapper.findTenantById(id);
        return tenantVo;
    }

    @Override
    public List<TenantVo> findTenantByIds(Long[] ids) {
        return userMapper.findTenantByIds(Arrays.asList(ids));
    }

    @Override
    public List<TenantVo> findTenants(String provinceCode, String cityCode, String districtCode, String streetCode) {
        return userMapper.findTenants(provinceCode, cityCode, districtCode, streetCode);
    }
    @Override
    @Transactional
    // *********************************************
    public String register(TenantVo tenantVo) {
        // 查询数据库是否有重复的账号
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getAccount,tenantVo.getAccount());
        User result = userMapper.selectOne(queryWrapper);
        if (!Objects.isNull(result)) {
            return ResultBean.FAIL;
        }
        // 进行数据库插入操作
        Long createId = 1271322350203121664L;
        Date now = new Date();
        Long id = IdWorker.getId();
        User user = new User();
        BeanUtils.copyProperties(tenantVo,user);
        user.setId(id);
        user.setUserType(2);
        user.setCreateId(createId);
        user.setCreateTime(now);
        user.setUpdateId(createId);
        user.setUpdateTime(now);
        userMapper.insert(user);
        return ResultBean.SUCCESS;
    }
}
